package com.ljx.comprehensiveCase.framework.beans;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 *
 * 用于储存和管理多个PropertyValue对象
 *
 * @作者 LJX
 * @日期 2022/12/27 14:50
 */
public class MultiplePropertyValues implements Iterable<PropertyValue>{

    //定义list集合对象，用来存储PropertyValue对象
    private final List<PropertyValue> propertyValueList;

    public MultiplePropertyValues() {
        this.propertyValueList = new ArrayList<>();
    }

    public MultiplePropertyValues(List<PropertyValue> propertyValueList) {
        if(null == propertyValueList){
            this.propertyValueList = new ArrayList<>();
        }else{
            this.propertyValueList = propertyValueList;
        }
    }

    /**
     * 获取迭代器对象
     * @return
     */
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }

    /**
     * 获取PropertyValue数组
     * @return
     */
    public PropertyValue[] getPropertyValueArr(){
        return propertyValueList.toArray(new PropertyValue[0]);
    }

    /**
     * 根据名称获取PropertyValue
     * @return
     */
    public PropertyValue getPropertyValueByName(String name){
        for (PropertyValue propertyValue : propertyValueList) {
            if(propertyValue.getName().equals(name)){
                return propertyValue;
            }
        }
        return null;
    }

    /**
     * 集合判空
     * @return
     */
    public Boolean isEmpty(){
        return propertyValueList.isEmpty();
    }

    /**
     * 添加PropertyValue 支持链式编程
     * @return
     */
    public MultiplePropertyValues addPropertyValue(PropertyValue pv){
        for (int i = 0; i < propertyValueList.size(); i++) {
            PropertyValue propertyValue = propertyValueList.get(i);
            //若已存在 则替换
            if(pv.getName().equals(propertyValue.getName())){
                propertyValueList.set(i, pv);
                return this;
            }
        }

        propertyValueList.add(pv);
        return this;
    }

    /**
     * 判断同名对象是否存在
     * @return
     */
    public Boolean contains(String name){
        return null != getPropertyValueByName(name);
    }

    @Override
    public void forEach(Consumer<? super PropertyValue> action) {
        Iterable.super.forEach(action);
    }

    @Override
    public Spliterator<PropertyValue> spliterator() {
        return Iterable.super.spliterator();
    }
}
